let ue = UE.getEditor("remark");
var zTree;
var setting = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/budgetget/getProjectTreeList",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    callback: {
        onClick: zTreeOnClick
    },
    view: {
        addHoverDom: addHoverDom,
        selectedMulti: false
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    }
};
$(function () {
    jeDate("#beginTime", {
        format: "YYYY-MM-DD",
        isinitVal: true
    });
    jeDate("#endTime", {
        format: "YYYY-MM-DD",
    });
    getBudgetTypeListForSelect();
    $.ajax({
        url: "/ret/budgetget/getProjectTreeList",
        type: "post",
        dataType: "json",
        success: function (data) {
            zTree = $.fn.zTree.init($("#tree"), setting, data);// 初始化树节点时，添加同步获取的数据
        }
    });

    $.ajax({
        url: "/ret/budgetget/getBudgetAccountTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            var topNode = [{
                sortName: "TOP分类",
                isParent: "false",
                sortId: ""
            }];
            var newTreeNodes = topNode.concat(data);
            $.fn.zTree.init($("#menuTree"), setting1, newTreeNodes);
        }
    });

    $("#budgetAccount").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });

    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });
})

var setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/budgetget/getBudgetAccountTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("menuTree"),
                nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#budgetAccount");
            idem.attr("data-value", vid);
            idem.val(v);
        }
    }
};


function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span").parent();
    $(".js-child-pro").remove();
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<a style='right: 5px;position: absolute;width: 100px;color: #F5F5F5;line-height: 15px;z-index: 9999999;' class='js-child-pro btn btn-success btn-xs' id='addBtn_" + treeNode.tId + "' onfocus='this.blur();'>添加子项目</a>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) {
        btn.bind("click", function () {
            document.getElementById("form2").reset();
            $("#childProjectModal").modal("show");
            $(".js-save").unbind("click").click(function () {
                console.log(treeNode.sortId);
                $.ajax({
                    url: "/set/budgetset/insertChildBudgetProject",
                    type: "post",
                    dataType: "json",
                    data: {
                        sortNo: $("#childSortNo").val(),
                        title: $("#childTitle").val(),
                        levelId: treeNode.sortId
                    },
                    success: function (data) {
                        if (data.status == "200") {
                            $("#childProjectModal").modal("hide");
                            var zTree = $.fn.zTree.getZTreeObj("tree");
                            zTree.addNodes(treeNode, {
                                sortId: data.list.projectId,
                                pId: treeNode.levelId,
                                sortName: data.list.title
                            });
                        } else if (data.status == "100") {
                            layer.msg(sysmsg[data.msg]);
                        } else if (data.status == "500") {
                            console.log(data.msg);
                        }
                    }
                })
            })
            return false;
        })
    }
}

function zTreeOnClick(event, treeId, treeNode) {
    $("#tipdiv").remove();
    if (treeNode.isParent) {
        $("#editdiv").hide();
        $("#listdiv").show();
        $("#myTable").bootstrapTable('destroy');
        query(treeNode.sortId)
    } else {
        $("#listdiv").hide();
        $("#editdiv").show();
        edit(treeNode.sortId, treeNode.levelId)
    }
}


function query(projectId) {
    $("#myTable").bootstrapTable({
        url: '/ret/budgetget/getBudgetChildProjectList?parentId=' + projectId,
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        striped: true,// 隔行换色
        cache: false,// 禁用缓存
        pagination: true,// 启动分页
        sidePagination: 'server',// 分页方式
        pageNumber: 1,// 初始化table时显示的页码
        pageSize: 10,// 每页条目
        showFooter: false,// 是否显示列脚
        showPaginationSwitch: false,// 是否显示 数据条数选择框
        sortable: true,// 排序
        search: false,// 启用搜索
        sortOrder: "asc",
        showColumns: false,// 是否显示 内容列下拉框
        showRefresh: false,// 显示刷新按钮
        idField: 'projectId',// key值栏位
        clickToSelect: false,// 点击选中checkbox
        pageList: [10, 20, 30, 50],// 可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        }, {
            field: 'num',
            title: '序号',// 标题 可不加
            width: '50px',
            formatter: function (value, row, index) {
                return index + 1;
            }
        }, {
            field: 'title',
            width: '200px',
            title: '项目名称',
            formatter:function (value,row,index)
            {
                return "<a href=\"javascript:void(0);details('" + row.projectId + "')\" style='cursor: pointer'>"+value+"</a>";
            }
        }, {
            field: 'projectCode',
            title: '项目编号',
            width: '100px'
        }, {
            field: 'chargeUser',
            width: '100px',
            title: '项目负责人',
            formatter: function (value, row, index) {
                return getUserNameByStr(value);
            }
        }, {
            field: 'beginTime',
            width: '100px',
            title: '开始时间'
        }, {
            field: 'endTime',
            width: '100px',
            title: '结束时间'
        }, {
            field: 'cashFrom',
            width: '100px',
            title: '资金来源'
        }, {
            field: 'budgetAccount',
            width: '50px',
            title: '预算科目',
            formatter: function (value, row, index) {
                return getBudgetAccountName(value);
            }
        }, {
            field: 'createUser',
            width: '50px',
            title: '立项人',
            formatter: function (value, row, index) {
                return getUserNameByStr(value);
            }
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            width: '120px',
            formatter: function (value, row, index) {
                return createOptBtn(row.projectId, row.levelId);
            }
        }],
        onClickCell: function (field, value, row, $element) {
            // alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, // 总页数,前面的key必须为"total"
                    rows: res.list.list
                    // 行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order
    };
    return temp;
};

function createOptBtn(projectId, levelId) {
    var html = "<a href=\"javascript:void(0);edit('" + projectId + "','" + levelId + "')\" class=\"btn btn-primary btn-xs\">编辑</a>&nbsp;&nbsp;" +
        "<a href=\"javascript:void(0);delectProject('" + projectId + "')\" class=\"btn btn-darkorange btn-xs\">删除</a>";
    return html;
}

function details(projectId) {
    window.open("/app/core/budget/projectdetails?projectId=" + projectId);
}

function edit(projectId, levelId) {
    $("#listdiv").hide();
    $("#editdiv").show();
    $("#show_attach").empty();
    $("#attach").attr("data_value","");
    $("#chargeUser").attr("data_value","");
    $("#budgetAccount").attr("data_value","");
    $("#joinUser").attr("data_value","");
    document.getElementById("form1").reset();
    ue.setContent("");
    $(".js-back-btn").unbind("click").click(function () {
        goback();
    })
    $.ajax({
        url: "/ret/budgetget/getBudgetProjectById",
        type: "post",
        dataType: "json",
        data: {projectId: projectId},
        success: function (data) {
            if (data.status == "200") {
                var info = data.list;
                for (var id in info) {
                    if (id == "remark") {
                        ue.setContent(info[id]);
                    } else if (id == "attach") {
                        $("#attach").attr("data_value", info[id]);
                        createAttach("attach", 4);
                    } else if (id == "chargeUser") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getUserNameByStr(info[id]));
                    } else if (id == "budgetAccount") {
                        $("#budgetAccount").attr("data-value", info[id]);
                        $("#budgetAccount").val(getBudgetAccountName(info[id]));
                    } else if (id == "levelId") {
                    } else if (id == "joinUser") {
                        $("#" + id).attr("data-value", info[id]);
                        $("#" + id).val(getUserNameByStr(info[id]));
                    } else {
                        $("#" + id).val(info[id]);
                    }
                }
                $(".js-update-save").unbind("click").click(function () {
                    updateProject(projectId, levelId);
                })
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }
        }
    });
}

function delectProject(projectId) {
    if (confirm(sysmsg['OPT_CONFIRM_DELETE'])) {
        $.ajax({
            url: "/set/budgetset/deleteBudgetProject",
            type: "post",
            dataType: "json",
            data: {
                projectId: projectId,
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else if (data.status == "500") {
                    console.log(data.msg);
                }
            }
        })
    }
}

function updateProject(projectId, levelId) {
    $.ajax({
        url: "/set/budgetset/updateBudgetProject",
        type: "post",
        dataType: "json",
        data: {
            projectId: projectId,
            sortNo: $("#sortNo").val(),
            title: $("#title").val(),
            projectCode: $("#projectCode").val(),
            projectType: $("#projectType").val(),
            chargeUser: $("#chargeUser").attr("data-value"),
            joinUser: $("#joinUser").attr("data-value"),
            levelId: levelId,
            totalCost: $("#totalCost").val(),
            beginTime: $("#beginTime").val(),
            endTime: $("#endTime").val(),
            cashFrom: $("#cashFrom").val(),
            budgetAccount: $("#budgetAccount").attr("data-value"),
            attach: $("#attach").attr("data_value"),
            remark: ue.getContext()
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                location.reload();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}


function getBudgetTypeName(budgetTypeId) {
    var returnStr = "";
    $.ajax({
        url: "/ret/budgetget/getBudgetTypeById",
        type: "post",
        dataType: "json",
        async: false,
        data: {
            budgetTypeId: budgetTypeId
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                returnStr = data.list.title;
            }
        }
    });
    return returnStr;
}


function getBudgetAccountName(budgetAccountId) {
    var returnStr = "";
    $.ajax({
        url: "/ret/budgetget/getBudgetAccountById",
        type: "post",
        dataType: "json",
        async: false,
        data: {
            budgetAccountId: budgetAccountId
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                returnStr = data.list.title;
            }
        }
    });
    return returnStr;
}

function goback() {
    $("#editdiv").hide();
    $("#listdiv").show();
}

function getBudgetTypeListForSelect() {
    $.ajax({
        url: "/ret/budgetget/getBudgetTypeListForSelect",
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.status == "200") {
                var list = data.list;
                var html = "<option>请选择分类</option>";
                for (var i = 0; i < list.length; i++) {
                    html += "<option value=\"" + list[i].budgetTypeId + "\">" + list[i].title + "</option>"
                }
                $("#projectType").html(html);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}
